//
//  AppDelegate.swift
//  BAweibo
//
//  Created by baggio on 2017/8/1.
//  Copyright © 2017年 baggio. All rights reserved.
//

import UIKit

@UIApplicationMain//这个标注的类是app的入口
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        //实例化window
        window=UIWindow(frame:UIScreen.main.bounds)
        window?.backgroundColor=UIColor.white
        
        //设置根控制器，修改根控制器可以测试页面
//        window?.rootViewController=BAMainViewController()
        window?.rootViewController = setUpRootVC()
        
        //设为主窗口并显示
        window?.makeKeyAndVisible()
        
        //注册切换根控制器的通知，通知是一对多的（注册是一端，发送是多端）
        //方法一
//        NotificationCenter.default.addObserver(self, selector: #selector(switchRootVC), name: BA_NOTIFICATION_SWITCH_ROOT_VC, object: nil)
        //方法二
        //闭包里面用到 self，循环引用
        NotificationCenter.default.addObserver(forName: BA_NOTIFICATION_SWITCH_ROOT_VC, object: nil, queue: nil) {[weak self] (noti) in
            self?.switchRootVC(noti: noti)
        }
        
        //测试可以放在这里
        
        
//        //测试 从沙盒获取 oAuthModel 数据
//        let vc = BAOAuthViewController()
//        let result=vc.getOAuthModelFromSandbox()
//        print(result)
        
        //沙盒路径
//        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
//        print(path)
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    //注销通知，deinit() 不能放在 extension 中
    deinit {
        NotificationCenter.default.removeObserver(self, name: BA_NOTIFICATION_SWITCH_ROOT_VC, object: nil)
    }

}


//与切换 rootViewController 相关
extension AppDelegate{
    
    //是否新版本
    private func isNewVersion() -> Bool {
        
        //当前的版本，info.plist 中的 "CFBundleShortVersionString"
        let currenVersion = Double(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)!
        //print(currenVersion)
        
        //之前的版本，保存在用户偏好中的，如果 key 不存在，则返回 0.0，自定义的 key "sandboxVersionKey"
        let oldVersion = UserDefaults.standard.double(forKey: "sandboxVersionKey")
        //print(oldVersion)
        
        if currenVersion != oldVersion {
            //保存当前的版本
            //UserDefaults.standard.set(currenVersion, forKey: "sandboxVersionKey")
            //userDefaults写数据的时候，不是立即写入，而且根据时间戳把缓存中的数据写入磁盘，有可能数据还没写入程序就终止了，所以要使用 synchronize() 强行同步写入
            let d = UserDefaults.standard
            d.set(currenVersion, forKey: "sandboxVersionKey")
            d.synchronize()
        }
        
        return currenVersion > oldVersion
    }
    
    
    fileprivate func setUpRootVC() ->  UIViewController {
        
        var retVC = UIViewController()
        
        if isNewVersion(){
            retVC = BANewFeatureViewController()
        }else{
            if BAOAuthViewModel.share.isLogin {
                retVC = BAWelcomeViewController()
            }else{
                retVC = BAMainViewController()
            }
        }
        return retVC
    }
    
    
    /*
     1.是否新版本
        是 -> 新特性(BANewFeatureViewController) -> 2
        否 -> 2
     2，BAMainViewController -> 是否 login
        是 -> 3
        否 -> BAMainViewController（访客视图）-> BAOAuthViewController（登录）-> 3
     3，BAWelcomeViewController -> BAMainViewController（登录状态）
     
     其中 -> BAMainViewController 和
         -> BAWelcomeViewController 和
         -> BAMainViewController(登录状态)
        这3步，需要使用通知
     
     noti: Notification 有3个值：
        fromNewFeatureVC2MainVC
        fromOAuthVC2WelcomeVC
        fromWelcomeVC2MainVc
     */
    @objc fileprivate func switchRootVC(noti: Notification) {
        var rootVC = UIViewController()
        let s = noti.object as! String
        
        if s == "fromNewFeatureVC2MainVC" {
            if BAOAuthViewModel.share.isLogin {
                rootVC = BAWelcomeViewController()
            }else{
                rootVC = BAMainViewController()
            }
        } else if s == "fromOAuthVC2WelcomeVC" {
            rootVC = BAWelcomeViewController()
        } else if s == "fromWelcomeVC2MainVC" {
            rootVC = BAMainViewController()
        }
        
        window?.rootViewController = rootVC
    }
}

